import React from 'react';
import { spaceClass } from './style';
import type { SpaceProps } from './types';

/** 是否是预设的间距大小 */
const isPresetSize = (size: SpaceProps['size']) => {
  return ['small', 'middle', 'large'].includes(size as string);
};

const Space: React.FC<SpaceProps> = (props) => {
  const {
    className,
    style,
    children,
    direction = 'horizontal',
    size = 'small',
    align = 'center',
    wrap = false,
    display = 'inline-flex',
    justify = 'start',
  } = props;

  // 先转换为数组
  const [rowGap, colGap] = Array.isArray(size) ? size : [size, size];
  const isPresetRowGap = isPresetSize(rowGap);
  const isPresetColGap = isPresetSize(colGap);

  const classes = spaceClass('_', className, direction, {
    // 是预设的间距大小，则添加对应的类名
    [`gap-row-${rowGap}`]: isPresetRowGap,
    [`gap-col-${colGap}`]: isPresetColGap,
    // 对齐方式
    [`align-${align}`]: !!align,
    [`justify-${justify}`]: !!justify,
    // 是否自动换行
    wrap,
  });

  // 不是预设大小，则传入的是数字，这里使用style来设置gap
  const gapStyle: React.CSSProperties = {};
  if (!isPresetRowGap) {
    gapStyle.rowGap = rowGap;
  }
  if (!isPresetColGap) {
    gapStyle.columnGap = colGap;
  }

  return (
    <div
      style={{
        ...gapStyle,
        ...style,
        display,
      }}
      className={classes}
    >
      {children}
    </div>
  );
};

export default Space;
